<?php

namespace App\Http\Controllers;

use App\Http\Middleware\AccessLog;
use App\Http\Middleware\AuthJWT;
use App\Models\MiniUser;
use App\Models\RoomCheckIn;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use Illuminate\Http\Request;
use EasyWeChat\Factory;


class WeChatController extends Controller
{
    public function __construct(){
//        $this->middleware(['jwt.custom.auth'])->except(['onLogin']);
        //除了主页之外

        //只有发布页
        //$this->middleware('auth', ['only' => 'create']);
    }
    private function getApp(): \EasyWeChat\MiniProgram\Application
    {
        $mini_config = config("wechat.mini_program.default");
        $storage_path = storage_path('logs/wechat/' );
        if (!file_exists($storage_path)) {
            mkdir($storage_path, 0775, true);
            chmod($storage_path, 0775);
        }
        $config = [
            'app_id' => $mini_config['app_id'],
            'secret' => $mini_config['secret'],
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => $storage_path.'/'.date("Ymd").'_wechat.log',
            ],
        ];
        return  Factory::miniProgram($config);
    }
    //
    public function serve(Request $request)
    {

        $signature = $request->get("signature");
        $timestamp = $request->get("timestamp");
        $nonce = $request->get("nonce");
        $data = $request->all();
        $signature = $data["signature"];
        //生成签名
        $timestamp = $data["timestamp"];
        $nonce = $data["nonce"];
        $token = "dapengkeyu";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        //签名比较,一致,返回随机字符
        LogFileSave((new \ReflectionClass(__CLASS__))->getShortName(),__FUNCTION__, ["request"=>$data,"tmpStr"=>$tmpStr]);
        if ($tmpStr == $signature ) {
            return (string) $data['echostr'];
        } else {
            LogFileSave((new \ReflectionClass(__CLASS__))->getShortName(),__FUNCTION__, ["request"=>$data,"tmpStr"=>"错误"]);
            return (string) false;
        }

//        $signature = $_GET["signature"];
//        $timestamp = $_GET["timestamp"];
//        $nonce = $_GET["nonce"];

        $token = "dapengkeyu";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        LogFileSave((new \ReflectionClass(__CLASS__))->getShortName(),__FUNCTION__, ["request"=>$request->all(),"tmpStr"=>$tmpStr]);
        try {
            if ($tmpStr == $signature ) {
                echo "true";die;

            }
            echo "false";die;
        }catch (\UnexpectedValueException $exception){
            echo 123;
            dd($exception->getFile(),$exception->getMessage(),$exception->getLine());
        }

    }

    public function onLogin(Request $request){
        $app  = $this->getApp();
        $code = $request->get("code");
    
        try {
            $info = $app->auth->session($code);
        } catch (InvalidConfigException $e) {

        };


        $name = 'wechat_user';
        $nickname = '微信用户';
        $name_py_f = getFullPinYin($nickname);
        $name_py_s = getShortpinyin($nickname);
        $openid = $info['openid'];
        $phone = '13810001000'; // 默认用户手机号 获取手机号时会更新
        $is_locked = 0;
        $access_token = '';
        $data = [
            'name' => $name,
            'openid' => $openid,
            'nickname' => $nickname,
            'name_py_f' => $name_py_f,
            'name_py_s' => $name_py_s,
            'email' => '',
            'phone' => $phone,
            'avator' =>'',
            'status' =>0,
            'updated_at' => date("Y-m-d H:i:s"),
            'created_at' => date("Y-m-d H:i:s"),
        ];

        $user = MiniUser::where([['openid', $openid]])->first();
        if ($user) {
            if ($user->status == 1) {
                return $this->success(200,"",$info);
            }
        }
        MiniUser::create($data);
        return $this->success(200,"",$info);
    }

    public function getUserPhone(Request $request)
    {
        $code = $request->get("code");
        $openid = $request->get('openid');
        $app = $this->getApp();
        $accessToken = $app->access_token;
        $token =  $accessToken->getToken();
        $response = $app->httpPostJson('wxa/business/getuserphonenumber?access_token='.$token['access_token'],[
            'code' => $code
        ]);
        if($response['errcode']!=0 || $response['errmsg']!="ok"){
            return $this->fail($response['errcode'],$response['errmsg'],[]);
        }
        $login_ip = $request->getClientIp();
        $login_at = date("Y_m-d H:i:s");
        $mini_user = MiniUser::where("openid",$openid)->first();
        $mini_user->access_token = $token['access_token'];
        $mini_user->phone = $response['phone_info']['phoneNumber'];
        $mini_user->last_login_at = $login_at;
        $mini_user->last_login_ip = $login_ip;
        $mini_user->updated_at = date("Y-m-d H:i:s");
        $mini_user->save();
        $rooms = RoomCheckIn::where("user_phone",$mini_user->phone)->first();
        if($rooms){
            $rooms->openid = $openid;
            $rooms->status = 1;
            $rooms->updated_at = date("Y-m-d H:i:s");
            $rooms->save();
        }
        return $this->success(200,'手机号获取成功',["user_info"=>$mini_user,"room_info"=>$rooms]);
    }
}
